<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 会员操作类
 * @package  htdocs
 * @subpackage  module/base
 * @author   allen.qiang
 * @version 1.0
 */

quanli_require('module/base/common/quanliCommon.class.php');
class customerHandler {

	private $dbca = null;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }


    /**
     * 删除会员收货地址
     * @param int $pcustID    会员号
     * @param int $deliverID  收货地址ID
     * @return array
     * @throws Exception
     */
    public function delCustDeliver($pcustID, $deliverID) {

        if (!isset($pcustID, $deliverID) || !is_numeric($pcustID) || !is_numeric($deliverID))
            return array( 'code' => 400, 'message' => '缺少参数' );

        try {

            //查询会员收货地址信息
            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->pcustID = $pcustID;
            $deliver_obj->deliverID = $deliverID;
            if (!$this->dbca->fetch($deliver_obj))
                throw new Exception('收货地址信息没有找到', 404);

            //删除会员收货地址
            $this->dbca->delete($deliver_obj);

            return array( 'code' => 200, 'message' => 'ok', 'data' => array() );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 删除发票信息
     * @param int $pcustID    会员号
     * @param int $invoiceID  发票号
     * @return array
     * @throws Exception
     */
    public function delCustInvoice($pcustID, $invoiceID) {

        if (!isset($pcustID, $invoiceID) || !is_numeric($pcustID) || !is_numeric($invoiceID))
            return array( 'code' => 400, 'message' => '缺少参数' );

        try {

            //查询会员发票信息
            $invoice_obj = new entity('cust_invoice');
            $invoice_obj->pcustID = $pcustID;
            $invoice_obj->invoiceID = $invoiceID;
            if (!$this->dbca->fetch($invoice_obj))
                throw new Exception('发票信息没有找到', 404);

            //删除发票
            $this->dbca->delete($invoice_obj);

            return array( 'code' => 200, 'message' => 'ok' );


        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 查询发票信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'pcustID' => int 会员号
            'invoiceID' => int 发票ID
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchCustInvoice( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //发票ID
        if (isset($arg_array['invoiceID']) && is_numeric($arg_array['invoiceID'])) {
            $sql .= ' AND invoiceID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['invoiceID'];
        }


        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_invoice ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM cust_invoice ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'pcustID' => $item->pcustID,
                    'invoiceID' => $item->invoiceID,
                    'invoice_type' => $item->invoice_type,
                    'invoice_title_type' => $item->invoice_title_type,
                    'invoice_title' => $item->invoice_title
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 订单结算
     * 查询会员全部发票信息
     * @param array $bill_master_array 订单数组
     * @param array $cust_buy_log 会员上次购买记录
     * @return array|null
     */
    public function checkoutInvoiceList( &$bill_master_array, &$cust_buy_log ) {

        //查询发票信息
        $arg_array = array(
            'pcustID' => $cust_buy_log['pcustID']
        );
        $invoice_array = $this->searchCustInvoice( $arg_array );

        if ($invoice_array) {
            foreach($invoice_array as &$invoice) {
                if ($invoice['invoiceID'] == $cust_buy_log['invoiceID']) {
                    $bill_master_array['invoice'] = 1;
                    $bill_master_array['invoiceID'] = $invoice['invoiceID'];
                    $bill_master_array['invoice_type'] = $invoice['invoice_type'];
                    $bill_master_array['invoice_title_type'] = $invoice['invoice_title_type'];
                    $bill_master_array['invoice_title'] = $invoice['invoice_title'];
                    $cust_buy_log['invoiceID'] = $bill_master_array['invoiceID'];
                }
            }

        }

        return $invoice_array;

    }


    /**
     * 订单结算
     * 查询选中的发票信息
     * @param array $bill_master_array 订单数组
     * @parma array $cust_buy_log 会员上次购买记录
     * @param int $invoiceID 选中的发票ID
     * @return array|null
     */
    public function checkoutInvoice( &$bill_master_array, &$cust_buy_log, $invoiceID ) {

    	if ($invoiceID) {
    	
	        //查询发票信息
	        $arg_array = array(
	            'pcustID' => $cust_buy_log['pcustID'],
	            'invoiceID' => $invoiceID
	        );
	        $invoice_array = $this->searchCustInvoice( $arg_array );
	        if (!$invoice_array)
	            return false;
	        $invoice = $invoice_array[0];
	
	        $bill_master_array['invoiceID'] = $invoice['invoiceID'];
	        $bill_master_array['invoice_type'] = $invoice['invoice_type'];
	        $bill_master_array['invoice_title_type'] = $invoice['invoice_title_type'];
	        $bill_master_array['invoice_title'] = $invoice['invoice_title'];
	
	        $cust_buy_log['invoiceID'] = $invoice['invoiceID'];
	
	        return true;
	        
        } else {
        	
        	$bill_master_array['invoice'] = 0;
        	$cust_buy_log['invoiceID'] = 0;
	
	        return true;
        }

    }



    /**
     * 添加/修改会员发票信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'invoice_type' => int 发票类型
            'invoice_title_type' => int 发票抬头类型
            'invoice_title' => string 发票抬头
            'pucstID' => int 会员号
            'creator' => int 创建/修改人
            'invoiceID' => int 发票ID【可选】
     * )
     * @return array
     * @throws Exception
     */
    public function editCustInvoice( $arg_array ) {

        if (!isset($arg_array['invoice_type'], $arg_array['invoice_title_type'], $arg_array['invoice_title'], $arg_array['pcustID'], $arg_array['creator']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (!in_array($arg_array['invoice_type'], array(1, 2)))
            return array( 'code' => 400, 'message' => '请选择发票类型' );

        if (!in_array($arg_array['invoice_title_type'], array(1, 2)))
            return array( 'code' => 400, 'message' => '请选择发票抬头类型' );

        if (empty($arg_array['invoice_title']))
            return array( 'code' => 400, 'message' => '发票抬头不能为空，请填写' );

        if (!isset($arg_array['invoiceID']) || !is_numeric($arg_array['invoiceID']) || $arg_array['invoiceID'] < 0)
            $arg_array['invoiceID'] = 0;

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        $arg_array['invoice_title'] = $commHandler->convertVar($arg_array['invoice_title']);

        try {

            $invoice_obj = new entity('cust_invoice');
            $invoice_obj->pcustID = $arg_array['pcustID'];
            if ($arg_array['invoiceID'] > 0) {
                $invoice_obj->invoiceID = $arg_array['invoiceID'];
                if (!$this->dbca->fetch($invoice_obj))
                    throw new Exception('发票信息没有找到，修改失败', 404);
                $invoice_obj->editor = $arg_array['creator'];
            } else {
                $invoice_obj->invoiceID = $commHandler->generate_seqno('seqno_invoice');
                $invoice_obj->creator = $arg_array['creator'];
            }
            $invoice_obj->invoice_type = $arg_array['invoice_type'];
            $invoice_obj->invoice_title_type = $arg_array['invoice_title_type'];
            $invoice_obj->invoice_title = $arg_array['invoice_title'];
            $this->dbca->save($invoice_obj);

            $invoice_array = array(
                'invoiceID' => $invoice_obj->invoiceID,
                'invoice_type' => $invoice_obj->invoice_type,
                'invoice_title_type' => $invoice_obj->invoice_title_type,
                'invoice_title' => $invoice_obj->invoice_title
            );


            return array( 'code' => 200, 'message' => 'ok', 'data' => $invoice_array );


        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 查询会员收货地址
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'pcustID' => int 会员号
            'deliverID' => int 收货地址号
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchCustDeliver( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //收货地址ID
        if (isset($arg_array['deliverID']) && is_numeric($arg_array['deliverID'])) {
            $sql .= ' AND deliverID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['deliverID'];
        }


        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_deliver ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM cust_deliver ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'pcustID' => $item->pcustID,
                    'deliverID' => $item->deliverID,
                    'provinceName' => $item->provinceName,
                    'cityName' => $item->cityName,
                    'countyName' => $item->countyName,
                    'provinceid' => $item->provinceid,
                    'cityid' => $item->cityid,
                    'countyid' => $item->countyid,
                    'address' => decryptD($item->address),
                    'custName' => decryptD($item->custName),
                    'postalCode'=>$item->postalCode,
                    'mobile' => decryptD($item->mobile),
                    'phone' => decryptD($item->phone)
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 订单结算
     * 查询会员收货地址列表
     * @param array $bill_master_array 订单数组
     * @param array $cust_buy_log 会员上次购买时的记录
     * @return null|array
     */
    public function checkoutDeliverList( &$bill_master_array, &$cust_buy_log ) {

        $arg_array = array(
            'pcustID' => $cust_buy_log['pcustID'],
            'sortname' => 'deliverID',
            'sortorder' => 'DESC'
        );

        //查询会员收货地址
        $deliver_array = $this->searchCustDeliver($arg_array);
        if (!$deliver_array)
            return null;

        foreach($deliver_array as $deliver) {
            if (!isset($bill_master_array['deliverid']) || $deliver['deliverID'] == $cust_buy_log['deliverID']) {
                $bill_master_array['deliverid'] = $deliver['deliverID'];
                $bill_master_array['deliver_province'] = $deliver['provinceName'];
                $bill_master_array['deliver_city'] = $deliver['cityName'];
                $bill_master_array['deliver_county'] = $deliver['countyName'];
                $bill_master_array['deliver_address'] = $deliver['address'];
                $bill_master_array['deliver_name'] = $deliver['custName'];
                $bill_master_array['deliver_postalCode'] = $deliver['postalCode'];
                $bill_master_array['deliver_mobile'] = $deliver['mobile'];
                $bill_master_array['deliver_phone'] = $deliver['phone'];
                $bill_master_array['countyid'] = $deliver['countyid'];
                $bill_master_array['cityid'] = $deliver['cityid'];
                $bill_master_array['provinceid'] = $deliver['provinceid'];
            }
        }

        $cust_buy_log['deliverID'] = $bill_master_array['deliverid'];

        return $deliver_array;

    }


    /**
     * 订单结算
     * 查询会员地址详情
     * @param array $bill_master_array 订单数组
     * @param array $cust_buy_log 会员上次购买时的记录
     * @param int $deliverID 选中的收货地址ID
     * @return bool
     */
    public function checkoutDeliver( &$bill_master_array, &$cust_buy_log, $deliverID ) {

        $arg_array = array(
            'pcustID' => $cust_buy_log['pcustID'],
            'deliverID' => $deliverID
        );

        //查询会员收货地址
        $deliver_array = $this->searchCustDeliver($arg_array);
        if (!$deliver_array)
            return false;

        $bill_master_array['deliverid'] = $deliverID;
        $bill_master_array['deliver_province'] = $deliver_array[0]['provinceName'];
        $bill_master_array['deliver_city'] = $deliver_array[0]['cityName'];
        $bill_master_array['deliver_county'] = $deliver_array[0]['countyName'];
        $bill_master_array['deliver_address'] = $deliver_array[0]['address'];
        $bill_master_array['deliver_name'] = $deliver_array[0]['custName'];
        $bill_master_array['deliver_mobile'] = $deliver_array[0]['mobile'];
        $bill_master_array['deliver_phone'] = $deliver_array[0]['phone'];
        $bill_master_array['countyid'] = $deliver_array[0]['countyid'];
        $bill_master_array['cityid'] = $deliver_array[0]['cityid'];
        $bill_master_array['provinceid'] = $deliver_array[0]['provinceid'];

        $cust_buy_log['deliverID'] = $deliverID;

        return true;

    }


    /**
     * 保存或修改会员地址信息
     * @param $arg_array
     * @return array
     * @throws Exception
     */
    public function editCustDeliver( $arg_array ) {

        if (!isset($arg_array['pcustID'], $arg_array['creator'], $arg_array['custName'], $arg_array['provinceid'], $arg_array['cityid'], $arg_array['countyid'],$arg_array['address'], $arg_array['mobile']))
            return array( 'code' => 400, 'message' => '参数错误' );
        if (!isset($arg_array['phone']))
            $arg_array['phone'] = null;

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        if (!empty($arg_array['deliverID']) && !is_numeric($arg_array['deliverID'])) {
        	return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (empty($arg_array['custName']))
            return array( 'code' => 400, 'message' => '收货人不能为空，请填写' );

        if (!is_numeric($arg_array['provinceid']) || !is_numeric($arg_array['cityid']) || !is_numeric($arg_array['countyid']) || $arg_array['provinceid'] <= 0
            || $arg_array['cityid'] <= 0 || $arg_array['countyid'] <= 0)
            return array( 'code' => 400, 'message' => '请选择省市区' );

        if (empty($arg_array['address']))
            return array( 'code' => 400, 'message' => '收货地址不能为空，请填写' );

        if (empty($arg_array['mobile']) && empty($arg_array['phone']))
            return array( 'code' => 400, 'message' => '“手机”和“固定电话”至少填写一项' );

        if (isset($arg_array['postalCode']) && !empty($arg_array['postalCode'])) {
        	if (strlen($arg_array['postalCode']) != 6 || !is_numeric($arg_array['postalCode'])) {
        		return array( 'code' => 400, 'message' => '请输入正确的邮编');
        	}
        } else {
            $arg_array['postalCode'] = null;
        }

        if (!empty($arg_array['mobile']) && !$commHandler->isMobile($arg_array['mobile']))
            return array( 'code' => 400, 'message' => '手机号码填写错误，格式：18612345678，请重新填写' );

        if (!empty($arg_array['phone']) && !$commHandler->isPhone($arg_array['phone']))
            return array( 'code' => 400, 'message' => '固定电话填写错误，格式：021-60745701，请重新填写' );

        if (!isset($arg_array['deliverID']) || !is_numeric($arg_array['deliverID']))
            $arg_array['deliverID'] = 0;

        try {

            //查询省份信息
            $province_obj = new entity('sys_region');
            $province_obj->id = $arg_array['provinceid'];
            $province_obj->region_level = 1;
            if (!$this->dbca->fetch($province_obj))
                throw new Exception('省份信息没有找到', 404);

            //查询市区信息
            $city_obj = new entity('sys_region');
            $city_obj->id = $arg_array['cityid'];
            $city_obj->region_level = 2;
            if (!$this->dbca->fetch($city_obj))
                throw new Exception('市区信息没有找到', 404);

            $county_obj = new entity('sys_region');
            $county_obj->id = $arg_array['countyid'];
            $county_obj->region_level = 3;
            if (!$this->dbca->fetch($county_obj))
                throw new Exception('地区信息没有找到', 404);

            //检查会员信息
            $cust_obj = new entity('cust_master');
            $cust_obj->pcustID = $arg_array['pcustID'];
            if (!$this->dbca->fetch($cust_obj))
                throw new Exception('会员信息没有找到', 404);


            //保存或更新会员地址信息
            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->pcustID = $arg_array['pcustID'];
            if ($arg_array['deliverID'] > 0) {

                $deliver_obj->deliverID = $arg_array['deliverID'];
                if (!$this->dbca->fetch($deliver_obj))
                    throw new Exception('收货地址没有找到', 404);
                $deliver_obj->editor  = $arg_array['creator'];

            } else {
                $deliver_obj->creator = $arg_array['creator'];
                $deliver_obj->deliverID = $commHandler->generate_seqno('seqno_custdeliver');
            }
            $deliver_obj->provinceName = $province_obj->name;
            $deliver_obj->cityName = $city_obj->name;
            $deliver_obj->countyName = $county_obj->name;
            $deliver_obj->provinceid = $province_obj->id;
            $deliver_obj->cityid = $city_obj->id;
            $deliver_obj->countyid = $county_obj->id;
            $deliver_obj->address = encryptD($commHandler->convertVar($arg_array['address']));
            $deliver_obj->custName = encryptD($commHandler->convertVar($arg_array['custName']));
            $deliver_obj->postalCode = $arg_array['postalCode'];
            $deliver_obj->mobile = encryptD($arg_array['mobile']);
            $deliver_obj->phone = encryptD($arg_array['phone']);
            $this->dbca->save($deliver_obj);

            $deliver_array = array(
                'pcustID' => $deliver_obj->pcustID,
                'deliverID' => $deliver_obj->deliverID,
                'provinceName' => $deliver_obj->provinceName,
                'cityName' => $deliver_obj->cityName,
                'countyName' => $deliver_obj->countyName,
                'provinceid' => $deliver_obj->provinceid,
                'cityid' => $deliver_obj->cityid,
                'countyid' => $deliver_obj->countyid,
                'address' => $arg_array['address'],
                'postalCode' => $arg_array['postalCode'],
                'custName' => $arg_array['custName'],
                'mobile' => $arg_array['mobile'],
                'phone' => $arg_array['phone']
            );

            return array( 'code' => 200, 'message' => 'ok', 'data' => $deliver_array );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 添加会员信息
     * @param array $arg_array 会员数据
     * @return array
     * @throws Exception
     */
    public function addCustomer( $arg_array ) {

		//检查参数
		if (!isset($arg_array['regName'], $arg_array['regPwd'], $arg_array['regPwd2'], $arg_array['custType']) || !is_numeric($arg_array['custType']))
			return array( 'code' => 400, 'message' => '参数错误', 'data' => 'regName' );
		
		//实例化公共类
		$commHandler = new commHandler( $this->dbca );

        //当会员为第三方会员注册时，只检测会员名是否为空
        if ($arg_array['custType'] == 3) {
        	if (empty($arg_array['regName'])) {
        		return array( 'code' => 400, 'message' => '会员名不能为空', 'data' => 'regName' );
        	}
        } elseif (!$commHandler->isMobile($arg_array['regName']) && !$commHandler->isEmail($arg_array['regName'])) {
            return array( 'code' => 400, 'message' => '会员名必须是手机号码或者邮箱', 'data' => 'regName' );
        }
		
        //检查密码
        if (!$commHandler->isPwd( $arg_array['regPwd'] )) {
            return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字或符号的组合', 'data' => 'regPwd' );
        } else if ($arg_array['regPwd'] != $arg_array['regPwd2']) {
            return array( 'code' => 400, 'message' => '两次输入密码不一致', 'data' => 'regPwd2' );
        }
		
        //会员名
        $custID = $arg_array['regName'];

        //密码
        $pwd = $arg_array['regPwd'];

        //第三方登录会员名
		$unionName = isset($arg_array['unionName']) ? trim($arg_array['unionName']) : null;

        //推荐人客户号
		$recom_pcustID = isset($_COOKIE['RECOMMEND']) && is_numeric($_COOKIE['RECOMMEND']) ? $_COOKIE['RECOMMEND'] : null;
		
        //email
        if (isset($arg_array['email']) && !empty($arg_array['email'])) {
            $email = trim($arg_array['email']);
        } else if ($commHandler->isEmail($custID)) {
            $email = $custID;
        } else {
            $email = null;
        }

        //手机号码
		if (isset($arg_array['mobile']) && !empty($arg_array['mobile'])) {
			$mobile = trim($arg_array['mobile']);
		} else if ($commHandler->isMobile($custID)) {
			$mobile = $custID;
		} else {
			$mobile = null;
		}

        //电话号码
        $phone = isset($arg_array['phone']) && $commHandler->isPhone($arg_array['phone']) ? $arg_array['phone'] : null;

        //性别
        $sexy = isset($arg_array['sexy']) && is_numeric($arg_array['sexy']) ? $arg_array['sexy'] : 0;

        //会员类型
        $custType = $arg_array['custType'];

        //生日
		$birthday = isset($arg_array['birthday']) && $commHandler->isDate($arg_array['birthday']) ? trim($arg_array['birthday']) : null;
		
		//卡号
		$cardNo = isset($arg_array['cardNo']) && !empty($arg_array['cardNo']) ? $arg_array['cardNo'] : null;
		
		//省
		$provinceName = isset($arg_array['provinceName']) && !empty($arg_array['provinceName']) ? $arg_array['provinceName'] : null;
		
		//市
		$cityName = isset($arg_array['cityName']) && !empty($arg_array['cityName']) ? $arg_array['cityName'] : null;
		
		//区
		$countyName = isset($arg_array['countyName']) && !empty($arg_array['countyName']) ? $arg_array['countyName'] : null;
		
        if ($custType == 4)
            $operator = $arg_array['operator'];

        try {

            //检查会员名是否已注册
            $cust_obj = new entity('cust_master');
            $cust_obj->custID = $custID;
            if ($this->dbca->fetch($cust_obj))
                throw new Exception('会员名已被使用，请使用其他会员名尝试注册', 406);


            //查询初始会员等级
            $rank_arg_array = array(
                'useFlg' => 1,
                'sortname' => 'rankID',
                'sortorder' => 'ASC'
            );
            $rank_array = $this->searchRank( $rank_arg_array );
            if (!$rank_array)
                throw new Exception('会员数据未初始化，注册失败', 406);

            $rankID = isset($arg_array['rankID']) && is_numeric($arg_array['rankID']) ? $arg_array['rankID'] : $rank_array[0]['rankID'];
			$rankName = isset($arg_array['rankName']) && !empty($arg_array['rankName']) ? $arg_array['rankName'] : $rank_array[0]['rankName'];
            
            //添加会员信息
            $cust_obj->pcustID = $commHandler->generate_seqno('seqno_customer');
            $cust_obj->creator = $custID;
            $cust_obj->rankID = $rankID;
            $cust_obj->rankName = $rankName;
            $cust_obj->pwd = md5($pwd);
            $cust_obj->useFlg = 1;
            $cust_obj->email = encryptD($email);
            $cust_obj->head_pic = 'default_user.gif';
            $cust_obj->unionName = $unionName;
            $cust_obj->birthday = $birthday;
            $cust_obj->mobile = encryptD($mobile);
            $cust_obj->phone = encryptD($phone);
            $cust_obj->recom_pcustID = $recom_pcustID;
            $cust_obj->sumAmt = 0;
            $cust_obj->isMobileVerify = 1;
            $cust_obj->cardNo = $cardNo; //卡号
            $cust_obj->provinceName = $provinceName; //省
            $cust_obj->cityName = $cityName; //市
            $cust_obj->countyName = $countyName; //区
            $cust_obj->custType = $arg_array['custType'];
            if (isset($arg_array['birthday'])) {
            	$cust_obj->birthday = $commHandler->convertVar($arg_array['birthday']);
            }
            if (isset($arg_array['custname'])) {
            	$cust_obj->custname = $commHandler->convertVar($arg_array['custname']);
            }
            if (isset($arg_array['nickName'])) {
            	$cust_obj->nickName = $commHandler->convertVar($arg_array['nickName']);
            }
            if (!$this->dbca->save($cust_obj))
                throw new Exception('页面已过期，请刷新页面重试', 406);

            $result_array = array(
                'pcustID' => $cust_obj->pcustID,
                'custID' => $custID,
                'email' => $email,
                'custType' => $custType,
                'mobile' => $mobile,
                'recom_pcustID' => $recom_pcustID
            );

            return array( 'code' => 200, 'message' => 'ok', 'data' => $result_array );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage(), 'field' => 'regName' );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误', 'data'=>$e->getMessage() );
            }

        }

	}


    /**
     * 修改会员信息
     * @param array $arg_array 参数数组
     * @return array
     * @throws Exception
     */
    public function editCustomer( $arg_array, &$eai ) {
		
        //检查参数
        if (!isset($arg_array['pcustID'], $arg_array['mobile'], $arg_array['email'], $arg_array['custname'], $arg_array['sexy']) || !is_numeric($arg_array['pcustID']))
            return array( 'code' => 400, 'message' => '参数错误' );

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

//        if (empty($arg_array['nickName'])) {
//            return array( 'code' => 400, 'message' => '昵称不能为空，请填写' );
//        }
        
        if (empty($arg_array['custname'])) {
            return array( 'code' => 400, 'message' => '真实姓名不能为空，请填写' );
        }
        
        if (empty($arg_array['email'])) {
            return array( 'code' => 400, 'message' => '电子邮件不能为空，请填写' );
        } else if (!$commHandler->isEmail($arg_array['email'])) {
            return array( 'code' => 400, 'message' => '电子邮件格式错误，请重新填写' );
        }

        if (empty($arg_array['mobile'])) {
            return array( 'code' => 400, 'message' => '手机号码不能为空，请填写' );
        } else if (!$commHandler->isMobile($arg_array['mobile'])) {
            return array( 'code' => 400, 'message' => '手机号码格式错误，请重新填写' );
        }

        if (!isset($arg_array['phone'])) {
            $arg_array['phone'] = null;
        } else if (!empty($arg_array['phone']) && !$commHandler->isPhone($arg_array['phone'])) {
            return array( 'code' => 400, 'message' => '电话号码格式错误，请重新填写' );
        }

        if (!isset($arg_array['sexy']) || !in_array($arg_array['sexy'], array(0, 1, 2))) {
            $arg_array['sexy'] = 0;
        }

        if (!isset($arg_array['identityCard']) || empty($arg_array['identityCard'])) {
            $arg_array['identityCard'] = null;
        }

        if (!isset($arg_array['maritalStatus']) || !in_array($arg_array['maritalStatus'], array(0, 1, 2))) {
            $arg_array['maritalStatus'] = 0;
        }

        if (!isset($arg_array['monthlyIncome']) || !in_array($arg_array['monthlyIncome'], array(0, 1, 2, 3, 4, 5))) {
            $arg_array['monthlyIncome'] = 0;
        }

        if (!isset($arg_array['provinceid']) || !is_numeric($arg_array['provinceid'])) {
            $arg_array['provinceid'] = 0;
        }

        if (!isset($arg_array['cityid']) || !is_numeric($arg_array['cityid'])) {
            $arg_array['cityid'] = 0;
        }

        if (!isset($arg_array['countyid']) || !is_numeric($arg_array['countyid'])) {
            $arg_array['countyid'] = 0;
        }

        if (!isset($arg_array['address']) || empty($arg_array['address'])) {
            $arg_array['address'] = null;
        }

        try {

            //查询省份
            if ($arg_array['provinceid'] == 0) {
                $province_array = null;
            } else {
                $region_array = array(
                    'id' => $arg_array['provinceid'],
                    'level' => 1
                );
                $province_array = $commHandler->searchRegion( $region_array );
            }

            //查询市区
            if ($arg_array['cityid'] == 0) {
                $city_array = null;
            } else {
                $region_array = array(
                    'id' => $arg_array['cityid'],
                    'parentID' => $arg_array['provinceid'],
                    'level' => 2
                );
                $city_array = $commHandler->searchRegion( $region_array );
            }

            //查询地区
            if ($arg_array['countyid'] == 0) {
                $county_array = null;
            } else {
                $region_array = array(
                    'id' => $arg_array['countyid'],
                    'parentID' => $arg_array['cityid'],
                    'level' => 3
                );
                $county_array = $commHandler->searchRegion( $region_array );
            }

            //检查会员名是否已注册
            $cust_obj = new entity('cust_master');
            $cust_obj->pcustID = $arg_array['pcustID'];
            if (!$this->dbca->fetch($cust_obj))
                throw new Exception('会员信息没有找到，请刷新页面重试', 406);

            if (isset($arg_array['nickName']) && !empty($arg_array['nickName'])){
            	$cust_obj->nickName = $commHandler->convertVar($arg_array['nickName']);
            }else {
            	$nickName = $cust_obj->custID;
            }
            //修改会员信息
            $cust_obj->custname = encryptD($commHandler->convertVar($arg_array['custname']));
            $cust_obj->sexy = $arg_array['sexy'];
            $cust_obj->email = encryptD($arg_array['email']);
            if (isset($arg_array['birthday'])) {
                $cust_obj->birthday = $arg_array['birthday'];
            }
            $cust_obj->mobile = encryptD($arg_array['mobile']);
            $cust_obj->phone = encryptD($arg_array['phone']);
            if (!empty($province_array)) {
                $cust_obj->provinceid = $province_array[0]['id'];
                $cust_obj->provinceName = $province_array[0]['name'];
            }
            if (!empty($city_array)) {
                $cust_obj->cityid = $city_array[0]['id'];
                $cust_obj->cityName = $city_array[0]['name'];
            }
            if (!empty($county_array)) {
                $cust_obj->countyid = $county_array[0]['id'];
                $cust_obj->countyName = $county_array[0]['name'];
            }
            $cust_obj->address = encryptD($commHandler->convertVar($arg_array['address']));
            $cust_obj->identityCard = encryptD($commHandler->convertVar($arg_array['identityCard']));
            $cust_obj->maritalStatus = $arg_array['maritalStatus'];
            $cust_obj->monthlyIncome = $arg_array['monthlyIncome'];
//            if (isset($arg_array['head_pic'])) {
//                $cust_obj->head_pic = $arg_array['head_pic'];
//            }
            if (!$this->dbca->save($cust_obj)) {
                throw new Exception('页面已过期，请刷新页面重试', 406);
            }

            $arg_array['provinceName'] = isset($cust_obj->provinceName) ? $cust_obj->provinceName : null;
            $arg_array['cityName'] = isset($cust_obj->cityName) ? $cust_obj->cityName : null;
            $arg_array['countyName'] = isset($cust_obj->countyName) ? $cust_obj->countyName : null;

            if (!isset($arg_array['nickName']) || empty($arg_array['nickName'])){
            	$arg_array['nickName'] = $nickName;
            }
            
            //调用会员资料修改接口
            $result_array = $eai->memberChangeInfo($arg_array, $this->dbca);
            
            if ($result_array['code'] != 200) {
                $eai->saveInterfaceFailLog($arg_array['pcustID'], 2, $this->dbca);
            }

            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            quanli_include('module/base/promotionHandler.class.php');    //加载促销活动类


            $promotionHandler = new promotionHandler( $this->dbca );  //实例化促销类


            $promotionHandler->grantCustPromotion( $cust_obj->pcustID, $cust_obj->custID, 6, $eai ); //查询会员促销活动并发放


            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            return array( 'code' => 200, 'message' => 'ok' );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 修改会员密码
     * @param array $arg_array 参数数组
     * $arg_array = array (
            'oldPwd' => string, 旧密码
            'newPwd' => string, 新密码
            'reNewPwd' => string, 确认新密码
     * )
     * @return array
     * @throws Exception
     */
    public function editCustPwd( $arg_array ) {

        //检查参数
        if (!isset($arg_array['oldPwd'], $arg_array['newPwd'], $arg_array['reNewPwd'],$arg_array['editor']))
            return array('code' => 400, 'message' => '参数错误');

        //实例化公共类
        $commHandler = new commHandler();

        //旧密码
        if (empty($arg_array['oldPwd']))
            return array('code' => 400, 'message' => '请输入正确的旧密码');

        //新密码
        if (!$commHandler->isPwd($arg_array['newPwd']))
            return array('code' => 400, 'message' => '新密码必须是6-30位字符，可使用字母、数字或符号的组');

        //重复新密码
        if ($arg_array['newPwd'] != $arg_array['reNewPwd'])
            return array('code' => 400, 'message' => '两次填写的新密码不一致，请重新填写');

        try {
			$this->dbca->beginTransaction();
            $customer_obj = new entity('cust_master');
            $customer_obj->pcustID = $arg_array['pcustID'];
            if (!$this->dbca->fetch($customer_obj))
                throw new Exception('会员信息没有找到，请重新登录', 404);

            if (strcasecmp($customer_obj->pwd, md5($arg_array['oldPwd'])) != 0)
                throw new Exception('旧密码不正确，请重新输入', 406);

            $customer_obj->pwd = md5($arg_array['newPwd']);
             $this->dbca->save($customer_obj);

            
            $this->dbca->commit();
            
            return array( 'code' => 200, 'message' => 'ok' );
            
        } catch (Exception $e) {
        	$this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }
    
    /**
     * 会员重置密码
     * @param array $arg_array 参数数组
     * 		string	$arg_array['mobile']	用户手机
     * 		string	$arg_array['newPwd']	用户新密码
     * 		string	$arg_array['reNewPwd']	确认新密码
     * 
     * @author yinfulin 2013-11-01
     * @return array
     * @throws Exception
     */
    public function resetCustPwd( $arg_array ) {

        //检查参数
        if (!isset($arg_array['mobile'], $arg_array['newPwd'], $arg_array['reNewPwd'], $arg_array['eai'],$arg_array['editor']))
            return array('code' => 400, 'message' => '参数错误');

        //实例化公共类
        $commHandler = new commHandler();

        //新密码
        if (!$commHandler->isPwd($arg_array['newPwd']))
            return array('code' => 400, 'message' => '新密码必须是6-30位字符，可使用字母、数字或符号的组');

        //重复新密码
        if ($arg_array['newPwd'] != $arg_array['reNewPwd'])
            return array('code' => 400, 'message' => '两次填写的新密码不一致，请重新填写');

        try {
			$this->dbca->beginTransaction();
            $customer_obj = new entity('cust_master');
            $customer_obj->custID = $arg_array['mobile'];
            if (!$this->dbca->fetch($customer_obj))
                throw new Exception('会员信息没有找到', 404);

			$old_pwd = $customer_obj->pwd;
			
            $customer_obj->pwd = md5($arg_array['newPwd']);
            $save_flg = $this->dbca->save($customer_obj);

            if ($save_flg) {
            	//同步调用crm接口	//added by yinfulin 2013-09-28 
	            $member_pwd_edit_result = $arg_array['eai']->memberEditPwd( $customer_obj->pcustID, $old_pwd, $arg_array['newPwd'], $arg_array['editor'], $this->dbca );

	            if (!$member_pwd_edit_result || !is_array($member_pwd_edit_result) || !isset($member_pwd_edit_result['code']) || $member_pwd_edit_result['code'] != 200) {
	            	throw new Exception(isset($member_pwd_edit_result['message']) ? $member_pwd_edit_result['message'] : '接口修改密码失败',500);
	            }
            }

            $this->dbca->commit();
            
            return array( 'code' => 200, 'message' => '密码重置成功' );
            
        } catch (Exception $e) {
        	$this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * searchConsult
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
        'pcustID' => int 会员号
        'sortname' => string 排序字段
        'sortorder' => string 排序方式
        'page' => int 分页页码
        'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchCustGoodsCollection ( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND cc.pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_collection cc ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY cc.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY cc.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT cc.pcustID,gs.* FROM cust_collection cc
                           INNER JOIN goods_sale gs ON gs.postID = cc.postID ' . $sql;;
            $item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$item_array)
                return null;

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 添加会员商品收藏
     * @param array $arg_array 参数数组
     * $arg_array = array (
            'postID' => int 三级网购号
            'pcustID' => int 会员号
            'creator' => string 创建人
     * )
     * @return array
     */
    public function addCustGoodsCollection( $arg_array ) {

        //检查参数
        if (!isset($arg_array['postID'], $arg_array['pcustID'], $arg_array['creator']) || empty($arg_array['creator']) || !is_numeric($arg_array['pcustID']) || !is_numeric($arg_array['postID']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        try {

            //检查会员是否已收藏该商品
            $collection_obj = new entity('cust_collection');
            $collection_obj->pcustID = $arg_array['pcustID'];
            $collection_obj->postID = $arg_array['postID'];
            if ($this->dbca->fetch($collection_obj))
                return array( 'code' => 404, 'message' => '商品已收藏' );

            //检查商品信息
            $goods_obj = new entity('goods_sale');
            $goods_obj->postID = $arg_array['postID'];
            if (!$this->dbca->fetch($goods_obj))
                return array( 'code' => 404, 'message' => '商品信息没有找到' );

            //添加会员商品收藏
            $collection_obj->creator = $arg_array['creator'];
            $this->dbca->save($collection_obj);

            return array( 'code' => 200, 'message' => '商品收藏成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }

    }



    /**
     * 删除客户商品收藏
     * @author 刘道健 hfldj@126.com
     * @param array  $params            参数数组
     * @param int    $params['postID']  网购号
     * @param int    $params['pcustID'] 客户号
     * @param object $dbca              数据库实例
     * @return -1：参数错误
     * 		   -4：删除商品收藏不存在
     * 		   -100：系统错误
     * 		    2：删除成功
     */
    public function delCustGoodsCollection( $arg_array ) {

        //检查参数
        if (!isset($arg_array['postID'], $arg_array['pcustID']) || !is_numeric($arg_array['pcustID']) || !is_numeric($arg_array['postID']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        try {

            //检查会员是否已收藏该商品
            $collection_obj = new entity('cust_collection');
            $collection_obj->pcustID = $arg_array['pcustID'];
            $collection_obj->postID = $arg_array['postID'];
            if (!$this->dbca->fetch($collection_obj))
                return array( 'code' => 404, 'message' => '收藏的商品不存在' );

            //删除会员收藏的商品
            $this->dbca->delete($collection_obj);

            return array( 'code' => 200, 'message' => '收藏商品删除成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }

    }



    /**
     * 查询会员等级信息
     * @param array $arg_array
     * $arg_array = array (
     *       'useFlg' => int 使用标志
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null
     */
	public function searchRank ( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //会员等级号
        if (isset($arg_array['rankID']) && is_numeric($arg_array['rankID'])) {
            $sql .= ' AND rankID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['rankID'];
        }

        //会员等级名称
        if (isset($arg_array['rankName']) && !empty($arg_array['rankName'])) {
            $sql .= ' AND rankName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['rankName'] . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_rank ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM cust_rank ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'rankID' => $item->rankID,
                    'rankName' => $item->rankName,
                    'needAmt' => $item->needAmt,
                    'rate' => $item->rate,
                    'pointsRate' => $item->pointsRate,
                    'freightFree' => $item->freightFree,
                    'discount_flg' => $item->discount_flg,
                    'useFlg' => $item->useFlg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

	}


    /**
     * 新增或修改会员等级
     * @param array $arg_array
     * @return array
     */
    public function editCustomerRank ( $arg_array ){

		if (!isset($arg_array['rankID'], $arg_array['rankName'], $arg_array['needAmt'], $arg_array['rate'], $arg_array['pointsRate'],
        $arg_array['discount_flg'], $arg_array['freightFree'], $arg_array['operator']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
		}

        if (empty($arg_array['rankName'])) {
            return array( 'code' => 400, 'message' => '等级名称不能为空' );
        }

        if (!is_numeric($arg_array['needAmt']) || $arg_array['needAmt'] < 0) {
            return array( 'code' => 400, 'message' => '累计消费金额必须为大于等于0的整数' );
        }

        if (!is_numeric($arg_array['rate']) || $arg_array['rate'] <= 0 || $arg_array['rate'] > 1) {
            return array( 'code' => 400, 'message' => '价格折扣必须为大于0，小于等于1的数字' );
        }

        if (!is_numeric($arg_array['pointsRate']) || $arg_array['pointsRate'] <= 0) {
            return array( 'code' => 400, 'message' => '赠送积分倍数必须为大于0的数字' );
        }

        if (!in_array($arg_array['discount_flg'], array(2, 1))) {
            return array( 'code' => 400, 'message' => '请选择折扣标识' );
        }

        if (!in_array($arg_array['freightFree'], array(0, 1))) {
            return array( 'code' => 400, 'message' => '请选择是否免运费' );
        }

        if ($arg_array['rankID'] < 0) {
            $arg_array['rankID'] = 0;
        }

		try {

			$rank_obj = new entity('cust_rank');
            if ($arg_array['rankID'] > 0) {
                $rank_obj->rankID = $arg_array['rankID'];
                if (!$this->dbca->fetch($rank_obj)) {
                    throw new Exception('会员等级信息没有找到', 404);
                }
                $rank_obj->editor = $arg_array['operator'];
            } else {
                $rank_obj->creator = $arg_array['operator'];
                $rank_obj->useFlg = 1;
            }
            $rank_obj->rankName = $arg_array['rankName'];
            $rank_obj->needAmt = $arg_array['needAmt'];
            $rank_obj->rate = $arg_array['rate'];
            $rank_obj->pointsRate = $arg_array['pointsRate'];
            $rank_obj->discount_flg = $arg_array['discount_flg'];
            $rank_obj->freightFree = $arg_array['freightFree'];

			$this->dbca->save($rank_obj);

            return array( 'code' => 200, 'message' => '保存成功' );

		} catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

		}
	}


    /**
     * 删除会员等级
     * @param array $rank_array
     * @return array
     */
    public function deleteCustomerRank ( $rank_array ) {

        if (!isset($rank_array) || empty($rank_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            foreach($rank_array as &$rankID) {
                $rank_obj = new entity('cust_rank');
                $rank_obj->rankID = $rankID;
                if (!$this->dbca->fetch($rank_obj)) {
                    continue;
                }
                $this->dbca->delete($rank_obj);
            }

            return array( 'code' => 200, 'message' => '删除成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }

	}

    public function changeRankUse( $rankID, $useFlg ) {

        if (!isset($rankID, $useFlg) || empty($rankID) || !in_array($useFlg, array(0, 1))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $rank_obj = new entity('cust_rank');
            $rank_obj->rankID = $rankID;
            if (!$this->dbca->fetch($rank_obj)) {
                throw new Exception('会员等级信息没有找到', 404);
            }
            if ($useFlg == 1) {
                $rank_obj->useFlg = 0;
            } else {
                $rank_obj->useFlg = 1;
            }
            $this->dbca->save($rank_obj);

            if ($rank_obj->useFlg) {
                return array( 'code' => 200, 'message' => '启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '禁用成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询会员资料
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'pcustID' => int 会员号
     *       'custID' => int 会员名
     *       'mobile' => string 手机号码
     *       'phone' => string电话号码
     *       'custname' => string 会员姓名
     * 		 'email'	=>string 邮箱
     * 		 'rankId'	=>int 会员等级
     *       'useFlg' => int 使用标志
     *       'startDate' => string 注册时间（开始）
     *       'endDate' => string 注册时间（结束）
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null
     */
    public function getCustomerInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //SQL字段类型字符串
        $params_type = '';

        //SQL字段值数组
        $params_array = array();

        //客户号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //用户名
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['custID'];
        }

        //手机号码
        if (isset($arg_array['mobile']) && !empty($arg_array['mobile'])) {
            $sql .= ' AND mobile = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['mobile']);
        }

        //电话号码
        if (isset($arg_array['phone']) && !empty($arg_array['phone'])) {
        	$sql .= ' AND phone LIKE ?';
        	$params_type .= 's';
        	$params_array[] = '%' . encrypt_paramD($arg_array['phone']) . '%';
        }

        //email
        if (isset($arg_array['email']) && !empty($arg_array['email'])) {
            $sql .= ' AND email = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['email']);
        }

        //用户姓名
        if (isset($arg_array['custname']) && !empty($arg_array['custname'])) {
            $sql .= ' AND custname LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . encrypt_paramD($arg_array['custname']) . '%';
        }

        //会员类型
        if ( isset($arg_array['customerType']) && !empty($arg_array['customerType']) ) {
        	$sql .= ' AND customerType = ? ';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['customerType'];
        }
        
        //会员等级
        if ( isset($arg_array['rankId']) && !empty($arg_array['rankId']) ) {
        	$sql .= ' AND rankID = ? ';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['rankId'];
        }
        
        //电话
        if ( isset($arg_array['phone']) && !empty($arg_array['phone']) ) {
        	$sql .= ' AND phone = ? ';
        	$params_type .= 's';
        	$params_array[] = encryptD($arg_array['phone']);
        }
        
        //邮箱
        if ( isset($arg_array['email']) && !empty($arg_array['email']) ) {
        	$sql .= ' AND email = ? ';
        	$params_type .= 's';
        	$params_array[] = encryptD($arg_array['email']);
        }

		if (isset($arg_array['timeStamp']) && !empty($arg_array['timeStamp'])) {
            $sql .= ' AND  timeStamp > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['timeStamp'];
        }
        
        //注册时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
        	$sql .= ' AND  createTime >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }
        
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
        	$sql .= ' AND  createTime <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_master ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }


            //查询分类信息
            $search_sql = 'SELECT * FROM cust_master ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;


            foreach ($temp_item_array as &$item) {

                //用户信息数组
                $item_array[]  = array(
                    'uuid'	    => 	$item->uuid,
                    'timeStamp'	=>	$item->timeStamp,
                    'creator' 	=> 	$item->creator,
                    'createTime' => $item->createTime,
                    'editor'	=> 	$item->editor,
                    'custID'	=> 	$item->custID,
                    'pcustID'	=> 	$item->pcustID,
                    'rankID'	=> 	$item->rankID,
                    'rankName'	=>	$item->rankName,
                    'pwd'		=> 	$item->pwd,
                    'custname'=>	decryptD($item->custname),
                    'sexy'	=>	$item->sexy,
                    'birthday'	=> 	$item->birthday,
                    'QQ'	=> 	$item->QQ,
                    'MSN'	=>	$item->MSN,
                    'email'	=>	decryptD($item->email),
                    'mobile'	=>	decryptD($item->mobile),
                    'phone'	=>	decryptD($item->phone),
                    'useFlg'	=>	$item->useFlg,
                    'useName'	=>	$item->useFlg ? '启用' : '禁用',
                    'head_pic'	=>	set_cust_head_pic( $item->head_pic ),
                    'custType'	=>	$item->custType,
                    'unionName'	=>	$item->unionName,
                    'sumAmt'	=>	$item->sumAmt,
                    'nickName' => $item->nickName,
                    'recom_pcustID' => $item->recom_pcustID,
                    'provinceid' => $item->provinceid,
                    'provinceName' => $item->provinceName,
                    'cityid' => $item->cityid,
                    'cityName' => $item->cityName,
                    'countyid' => $item->countyid,
                    'countyName' => $item->countyName,
                    'address' => decryptD($item->address),
                    'identityCard' => decryptD($item->identityCard),
                    'maritalStatus' => $item->maritalStatus,
                    'monthlyIncome' => $item->monthlyIncome,
                    'reserved_info'	=> $item->reserved_info,
                    'cardNo' => $item->cardNo
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询客户收藏表数据
     * @param array  $arg_array                          查询参数数组
     * $arg_array = array(
            'sortname' => string, 排序字段
            'sortorder' => string, 排序方式
            'page' => int, 分页页数
            'rp' => int, 分页页数
     * )
     * @return array
     */
    public function searchCollection( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //客户号
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
        	$sql .= ' AND cc.pcustID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['pcustID'];
        }

        //网购号
        if (isset($arg_array['postID']) && !empty($arg_array['postID']) && is_numeric($arg_array['postID'])) {
			$sql .= ' AND cc.postID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['postID'];
        }

        //网购号
        if (isset($arg_array['twoPostID']) && !empty($arg_array['twoPostID']) && is_numeric($arg_array['twoPostID'])) {
        	$sql .= ' AND gs.twoPostID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['twoPostID'];
        }
        
        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        $collection_list = array(); //客户收藏数组

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_collection cc ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY cc.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY cc.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
            }

            //查询分类信息
            $search_sql = 'select cc.uuid,cc.creator,cc.createTime,cc.pcustID,cc.postID,
            					gs.goodsName,gs.marketPrice,gs.salePrice,gs.goodsMainPic
            					from cust_collection cc
								inner join goods_sale gs on cc.postID=gs.postID '. $sql;
            $collection_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if ($collection_array) {
            	foreach ($collection_array as $collection) {
            		$collection_list[] = array(
            			'uuid' => $collection->uuid,
            			'creator' => $collection->creator,
            			'createTime' => $collection->createTime,
            			'pcustID' => $collection->pcustID,
            			'postID' => $collection->postID,
            			'goodsName' => $collection->goodsName,
            			'marketPrice' => $collection->marketPrice,
            			'salePrice' => $collection->salePrice,
            			'goodsLink' => set_goods_link($collection->postID),
            			'wap_link' => set_wap_goods_link($collection->postID),
            			'pictureLink' => set_goods_img_link($collection->goodsMainPic)
            		);
            	}
            }

            return $collection_list;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }


    /**
     * 查询会员最后一次购买记录
     * @param int $pcustID 会员号
     * @return array
     */
    public function searchCustBuyLog( $pcustID ) {

        //sql字符串
        $sql = '';

        //SQL字段类型字符串
        $params_type = '';

        //SQL字段值数组
        $params_array = array();

        $item_array = array(
            'pcustID' => $pcustID,
            'deliverID' => 0,
            'send_region_id' => 0,
            'payTypeID' => 0,
            'pay_type' => 0,
            'payment_method_id' => 0,
            'invoiceID' => 0,
            'send_time_id' => 0,
            'extend_1' => 0,
            'extend_2' => 0,
            'extend_3' => 0,
            'extend_4' => 0,
            'extend_5' => 0,
            'extend_6' => 0
        );

        if (!isset($pcustID) || !is_numeric($pcustID))
            return $item_array;

        //客户号
        $sql .= ' WHERE pcustID = ?';
        $params_type .= 'i';
        $params_array[] = $pcustID;

        try {


            //查询分类信息
            $search_sql = 'SELECT * FROM bill_cust_buy_log ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return $item_array;

            $item_array = array(
                'pcustID' => $temp_item_array[0]->pcustID,
                'deliverID' => $temp_item_array[0]->deliverID,
                'send_region_id' => $temp_item_array[0]->send_region_id,
                'payTypeID' => $temp_item_array[0]->payTypeID,
                'pay_type' => $temp_item_array[0]->pay_type,
                'payment_method_id' => $temp_item_array[0]->payment_method_id,
                'invoiceID' => $temp_item_array[0]->invoiceID,
                'send_time_id' => $temp_item_array[0]->sendTimeID,
                'extend_1' => $temp_item_array[0]->extend_1,
                'extend_2' => $temp_item_array[0]->extend_2,
                'extend_3' => $temp_item_array[0]->extend_3,
                'extend_4' => $temp_item_array[0]->extend_4,
                'extend_5' => $temp_item_array[0]->extend_5,
                'extend_6' => $temp_item_array[0]->extend_6
            );


            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 添加或编辑账户异动
     * @param array $arg_array 参数数组
     * $arg_array = array ()
     * @return array
     */
    public function saveAccountChange( $arg_array ) {

    	//用户名
        if (!isset($arg_array['custID']) || empty($arg_array['custID'])) {
        	return array( 'code' => 400, 'message' => '用户名不能为空' );
        }

        //异动账户不能为空
        if (!isset($arg_array['payTypeID']) || empty($arg_array['payTypeID'])) {
        	return array( 'code' => 400, 'message' => '异动账户不能为空' );
        }

        //金额不能为空
        if (!isset($arg_array['changeAmount']) || empty($arg_array['changeAmount'])) {
        	return array( 'code' => 400, 'message' => '金额不能为空' );
        }

        //来源
        if (!isset($arg_array['sourceID']) || empty($arg_array['sourceID'])) {
        	return array( 'code' => 400, 'message' => '来源不能为空' );
        }

        try {

        	//检查用户是否存在
        	$search_cust_array = array(
        		'custID' => $arg_array['custID']
        	);
        	$result = $this->getCustomerInfo( $search_cust_array );
        	if(!isset($result[0]) || empty($result[0])){
				return array( 'code' => 406, 'message' => '用户不存在' );
			} else {
				$result = $result[0];
			}

			//查询用户账户
//			$arg_account_array = array(
//				'custID' => $arg_array['custID'],
//				'payTypeID' => $arg_array['payTypeID'],
//				'pcustID' => $result['pcustID']
//			);
			$result2 = $_REQUEST['eai']->memberAccount( $result['pcustID'], $arg_array['payTypeID'],$this->dbca);
			if (isset($result2['data']) && isset($result2['data']['useableAccount'])) {
				$useableAccount = $result2['data']['useableAccount'];
			} else {
				$useableAccount = 0;
			}

			//计算金额和积分
			if ($arg_array['type'] == 1) {
				$result_account = $useableAccount + $arg_array['changeAmount'];
			} else {
				$result_account = $useableAccount - $arg_array['changeAmount'];
			}

			if ($result_account < 0) {
				if($arg_array['payTypeID'] == 2){
	 				return array( 'code' => 406, 'message' => '您的余额不足' );
	 			}else{
	 				return array( 'code' => 406, 'message' => '您的剩余积分不足' );
	 			}
			}

			//判断来源
			if($arg_array['sourceID'] == 0){
				return array( 'code' => 406, 'message' => '您还没选择来源' );
		 	}else{
		 		$sourceID = $arg_array['sourceID'];
		 	}

		 	$arg_item_array = array(
		 		'itemID' => $sourceID
		 	);

		 	$itemHandler = new itemHandler( $this->dbca );
		 	$list_array = $itemHandler->searchItem( $arg_item_array );
		 	if (!$list_array) {
		 		return array( 'code' => 406, 'message' => '该来源不存在' );
		 	}

			//获取当前创建时间
			$datetime = date("Y-m-d h:i:s");

			$save_array = new entity('cust_finance_change');

			if (isset($arg_array['changeID']) && !empty($arg_array['changeID'])) { //编辑
				$save_array->changeID = $arg_array['changeID'];
				if (!$this->dbca->fetch($save_array)) {
					return array( 'code' => 406, 'message' => '编辑对象没有找到');
				}
			}

			$save_array->creator = $arg_array['creator'];
			$save_array->createTime = $datetime;
			$save_array->custID = $arg_array['custID'];
			$save_array->pcustID = $result['pcustID'];
			$save_array->custname = $arg_array['creator'];
			$save_array->payTypeID = $arg_array['payTypeID'];
			if($arg_array['payTypeID'] == 2){
				$save_array->payTypeName = '余额';
			}else{
				$save_array->payTypeName = '积分'; //3
			}

			$save_array->sourceID = $sourceID;
			$save_array->sourceName = $list_array[0]['itemName'];
			if ($arg_array['type'] == 1) { //充值
				$save_array->changeAmount = $arg_array['changeAmount'];
			} else { //消费
				$save_array->changeAmount = 0 - $arg_array['changeAmount'];
			}

			$save_array->remark = $arg_array['remark'];
			if (isset($arg_array['changeStatus']) && !empty($arg_array['changeStatus'])) {
				$save_array->changeStatus = $arg_array['changeStatus'];
			} else {
				$save_array->changeStatus = 1;
			}

		 	$this->dbca->save($save_array,'customer');

		 	return array( 'code' => 200, 'message' => '保存成功' );

        } catch (Exception $e) {
        	error_log($e->getMessage());
        	return array( 'code' => 500, 'message' => '系统异常,请与系统管理员联系' );
        }
    }

    /**
     * 查询账户异动信息
     * @param array  $arg_array                          查询参数数组
     * $arg_array = array(
            'sortname' => string, 排序字段
            'sortorder' => string, 排序方式
            'page' => int, 分页页数
            'rp' => int, 分页页数
     * )
     * @return array
     */
    public function searchFinanceInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //客户号
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
        	$sql .= ' AND pcustID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['pcustID'];
        }

        //流水号
        if (isset($arg_array['changeID']) && !empty($arg_array['changeID']) && is_numeric($arg_array['changeID'])) {
        	$sql .= ' AND changeID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['changeID'];
        }

        //用户名
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
        	$sql .= ' AND custID = ?';
        	$params_type .= 's';
        	$params_array[] = $arg_array['custID'];
        }

        //异动账户ID
        if (isset($arg_array['payTypeID']) && !empty($arg_array['payTypeID']) && is_numeric($arg_array['payTypeID'])) {
        	$sql .= ' AND payTypeID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['payTypeID'];
        }

        //账户来源
        if (isset($arg_array['sourceID']) && !empty($arg_array['sourceID']) && is_numeric($arg_array['sourceID'])) {
        	$sql .= ' AND sourceID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['sourceID'];
        }

        //异动状态
        if (isset($arg_array['changeStatus']) && !empty($arg_array['changeStatus']) && is_numeric($arg_array['changeStatus'])) {
        	$sql .= ' AND changeStatus = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['changeStatus'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        $account_list = array(); //账户异动数据数组

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM  cust_finance_change ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
            }

            //查询分类信息
            $search_sql = 'SELECT * FROM cust_finance_change '. $sql;
            $account_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if ($account_array) {
            	foreach ($account_array as $account) {
            		$account_list[] = array(
            			'uuid' => $account->uuid,
            			'timeStamp' => $account->timeStamp,
            			'creator' => $account->creator,
            			'createTime' => $account->createTime,
            			'editor' => $account->editor,
            			'changeID' => $account->changeID,
            			'pcustID' => $account->pcustID,
            			'custID' => $account->custID,
            			'custname' => $account->custname,
            			'payTypeID' => $account->payTypeID,
            			'payTypeName' => $account->payTypeName,
            			'sourceID' => $account->sourceID,
            			'sourceName' => $account->sourceName,
            			'changeAmount' => $account->changeAmount,
            			'remark' => $account->remark,
            			'changeStatus' => $account->changeStatus
            		);
            	}
            }

            return $account_list;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }

    /**
     * 根据会员号得到会员等级信息
     * @param int $pcustID
     * @return array
     */
    public function getCustRand( $pcustID ) {

        if (!is_null($pcustID)) {

            //查询会员信息
            $cust_obj = new entity('cust_master');
            $cust_obj->pcustID = $pcustID;
            if ($this->dbca->fetch($cust_obj)) {

                //查询会员等级信息
                $rank_obj = new entity('cust_rank');
                $rank_obj->rankID = $cust_obj->rankID;
                if ($this->dbca->fetch($rank_obj)) {

                    return array(
                        'rate' => $rank_obj->rate,
                        'pointsRate' => $rank_obj->pointsRate,
                        'freightFree' => $rank_obj->freightFree,
                        'discount_flg' => $rank_obj->discount_flg,
                    );

                }

            }

        }

        return array(
            'rate' => 1,
            'pointsRate' => 1,
            'freightFree' => 1,
            'discount_flg' => 1,
        );

    }

    /**
	 * 生成数字验证码
	 * @param array $params 请求参数
	 * 			int	$params['num']	验证码位数
	 */
	public function getRandNumber($params){
		if (!isset($params['num'])) {
			return array('code'=>400,'message'=>'验证码位数不能为空');
		}

		$numArr = range(0,9);
		shuffle($numArr);
		$newArr = array_rand($numArr,$params['num']);
		$randomStr = '';
		foreach($newArr as $value){
			$randomStr .= $numArr[$value];
		}
		return array('code'=>200,'message'=>'获取成功','data'=>$randomStr);
	}

	/**
	 * 发送短信
	 * @param  array	$params
	 * 		string		$params['recipient']	收信人
	 * 		string		$params['smsContent']	短信内容
	 */

	public function sendSMS($params){
		global $G_SHOP;

//		$randomStr = "尊敬的顾客，您本次的手机验证码为 ".$params['smsContent']."，转发无效。";
		$sms_url = 'http://hy6.nbark.com:7602';
		$companyUser = iconv('utf-8','GB2312','nbhaoerwanjiahy');
		$companyUser = urlencode($companyUser);
		$companyPwd = iconv('utf-8','GB2312','haoerwanjia0929');
		$companyPwd = urlencode($companyPwd);
		$MessageContent = iconv('utf-8','GB2312',$params['smsContent']);
		$MessageContent = urlencode($MessageContent);
		$phone = iconv('utf-8','GB2312',$params['recipient']);
		$tel = urlencode($params['recipient']);
		$requestStr = $sms_url.'/sms.aspx?action=send&userid=64&account='. $companyUser .'&password='. $companyPwd .'&mobile='. $params['recipient'] .'&content='. urlencode($params['smsContent']) .'&sendTime=&extno=';

		$ch = curl_init();//初始化
     	curl_setopt($ch, CURLOPT_URL, $requestStr);
	 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	 	curl_setopt($ch, CURLOPT_HEADER, 0);
		$output = curl_exec($ch);

		$object_result = simplexml_load_string($output);
		if ($object_result && isset($object_result->returnstatus) && $object_result->returnstatus== 'Success') {
			return true;
		}else{
			return false;
		}
//		$str =  urldecode($output);
//		$str = iconv('GB2312','utf-8',$str);
//		$arr = explode('&',$str);//将获得结果打散成数组
//		if($arr[0] == 'result=0'){
////			$G_SHOP->sessionCahce_set('dxyzm',md5($code),3600);//将验证码信息保存到memcache中去
//			return true;
//		}else{
//			return false;
//		}
	}



    /**
     * 查询会员投诉信息
     * @param array  $arg_array                          查询参数数组
     * $arg_array = array(
     *   'sortname' => string, 排序字段
     *   'sortorder' => string, 排序方式
     *   'page' => int, 分页页数
     *   'rp' => int, 分页页数
     * )
     * @return array
     */
    public function searchCustComplaint( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //投诉ID
        if (isset($arg_array['complaintID']) && !empty($arg_array['complaintID']) ) {
            $sql .= ' AND complaintID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['complaintID'];
        }

        //联系手机
        if (isset($arg_array['mobile']) && !empty($arg_array['mobile']) ) {
            $sql .= ' AND mobile = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['mobile']);
        }

        //订单号
        if (isset($arg_array['bill_no']) && !empty($arg_array['bill_no']) ) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['bill_no']);
        }

        //客户号
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //用户名
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['custID']);
        }

        //投诉类型
        if (isset($arg_array['complaintType']) && !empty($arg_array['complaintType'])) {
            $sql .= ' AND complaintType = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['complaintType']);
        }

        //投诉日期
        if ( !empty($arg_array['startDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND createTime >= ? AND createTime <= ?';
            $params_type .= 'ss';
            $params_array[] = trim($arg_array['startDate']) . ' 00:00:00';
            $params_array[] = trim($arg_array['endDate']) . ' 23:59:59';
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        $complaint_list = array(); //返回数组

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM  cust_complaint ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
            }

            //查询分类信息
            $search_sql = 'SELECT * FROM cust_complaint '. $sql;
            $complaint_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if ($complaint_array) {
                foreach ($complaint_array as $complaint) {
                    $complaint_list[] = array(
                        'uuid' => $complaint->uuid,
                        'timeStamp' => $complaint->timeStamp,
                        'creator' => $complaint->creator,
                        'createTime' => $complaint->createTime,
                        'complaintID' => $complaint->complaintID,
                        'bill_no' => $complaint->bill_no,
                        'pcustID' => $complaint->pcustID,
                        'custID' => $complaint->custID,
                        'complaintType' => $complaint->complaintType,
                        'complaintContent' => $complaint->complaintContent,
                        'memo' => $complaint->memo,
                        'mobile' => $complaint->mobile,
                        'operator' => $complaint->operator,
                        'operateTime' => $complaint->operateTime,
                        'status' => $complaint->status,
                        'msg' => $complaint->msg
                    );
                }
            }

            return $complaint_list;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }

    /**
     * 新增或编辑客户投诉信息
     *$arg_array 参数数组
     */
    function addCustComplaint( $arg_array ){

        if( !isset( $arg_array['operator'] , $arg_array['mobile'], $arg_array['complaintType'] , $arg_array['memo'] ) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        //接收参数
        $custID = isset( $arg_array['custID'] ) ? trim( $arg_array['custID'] ) : '';
        $bill_no = isset($arg_array['bill_no']) ? trim( $arg_array['bill_no'] ) : '';
        $complaintType = trim( $arg_array['complaintType'] );
        $memo = htmlspecialchars( trim( $arg_array['memo'] ) );
        $mobile = trim( $arg_array['mobile'] );
        $complaintID = isset( $arg_array['complaintID'] ) ? $arg_array['complaintID'] : '';

        if( empty($complaintType) )
            return array( 'code'=>400 , 'message'=>'投诉类型不能为空' );

        if( empty($memo) )
            return array( 'code'=>400 , 'message'=>'投诉内容不能为空' );

        if( empty($mobile) ){
            return array( 'code'=>400 , 'message'=>'联系手机不能为空' );
        }else{

            if( !$commHandler->isMobile($mobile) )
                return array( 'code'=>400 , 'message'=>'手机格式有误' );

        }

        if( !empty($bill_no) && !is_numeric($bill_no) )
            return array( 'code'=>400 , 'message'=>'订单号必须是整数序列' );


        //实例化字典表操作公共类
        $itemHandler = new itemHandler( $this->dbca );

        //查询投诉类型信息
        $params['itemID'] = $arg_array['complaintType'];
        $params['item']   = 13;  //投诉类型分类ID
        $itemResult = $itemHandler->searchItemList( $params );

        if( empty($itemResult) )
            return array( 'code'=>404 , 'message'=>'没有找到投诉类型信息' );

        //如果存在订单，查询订单信息
        if( !empty($bill_no) ){

            //从订单主表查询订单信息
            $search_bill_sql = 'SELECT * FROM bill_master WHERE bill_no = ?';
            $billInfo        = $this->dbca->stmt_query( $search_bill_sql , 's' ,  $_REQUEST['bill_no']);

            if( empty($billInfo) )
                return array( 'code'=>404 , 'message'=>'['.$_REQUEST['bill_no'].']订单不存在' );

        }

        //如果存在用户名，则查询用户信息
        if( !empty($custID) ){

            //查询会员信息
            $custData = $this->getCustomerInfo( $arg_array );

            if( empty($custData) )
                return array( 'code'=>404 , 'message'=>'没有找到['.trim($arg_array['custID']).']会员信息' );

        }

        try{

            //事务开启
            $this->dbca->beginTransaction();

            //创建对象
            $complaint_obj = new entity('cust_complaint');

            if( $complaintID ){

                $complaint_obj->complaintID = $complaintID;

                if( !$this->dbca->fetch($complaint_obj) )
                    return array( 'code'=>404 , 'message'=>'没有找到信息');

            }else{

                $complaint_obj->creator = $arg_array['operator'];

            }

            $complaint_obj->bill_no = $bill_no;
            $complaint_obj->pcustID = $custData[0]['pcustID'];
            $complaint_obj->custID = $custID;
            $complaint_obj->complaintType = $complaintType;
            $complaint_obj->complaintContent = $itemResult[0]->itemName;
            $complaint_obj->memo = $memo;
            $complaint_obj->mobile = $mobile;
            $complaint_obj->operator = NULL;
            $complaint_obj->operateTime = NULL;
            $complaint_obj->status = 0;
            $complaint_obj->msg = NULL;

            $this->dbca->save( $complaint_obj );

            //提交事务
            $this->dbca->commit();

            if( $complaintID ){
                return array( 'code'=>200 , 'message'=>'更新成功');
            }else{
                return array( 'code'=>200 , 'message'=>'添加成功');
            }

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            error_log( $e->getMessage() );
            return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

        }

    }

    /**
     * 查询会员卡激活信息
     * @param int $pcustID 会员号
     * @return array|null
     */
    public function searchCustomerActivate( $pcustID ) {

        $search_sql = 'SELECT * FROM cust_card_active WHERE pcustID = ?';
        $activate_array = &$this->dbca->stmt_query($search_sql, 'i', $pcustID);
        if (!$activate_array) {
            return null;
        }
        foreach($activate_array as &$item) {
            $item_array = array(
                'pcustID' => $item->pcustID,
                'is_active' => $item->is_active
            );
        }
        return $item_array;

    }
    
    //根据传入的省市区名称，获得对应的区域ID
    public function getRegionID( $arg ){
    	
    	$provinceName = isset($arg['provinceName']) ? trim($arg['provinceName']) : '';
    	$cityName = isset($arg['cityName']) ? trim($arg['cityName']) : '';
    	$districtName = isset($arg['districtName']) ? trim($arg['districtName']) : '';
    	if (empty($provinceName)){
    		return null;
    	}
    	
    	$provinceid = '';
    	$cityid = '';
    	$countyid = '';
    	
    	$sql = 'SELECT id, name, parentID, region_level FROM sys_region ORDER BY parentID ASC';
    	$result = $this->dbca->stmt_query($sql);
    	if (!$result){
    		return null;
    	}
    	
    	$parentID = 0;
    	foreach ($result as $value){
    		if ($value->name == $provinceName && $value->parentID == $parentID && $value->region_level == 1){
    			$provinceid = $value->id;
    			$parentID = $value->id;
    			if (empty($cityName)){
    				break;
    			}
    		}
    		
    		if ($value->name == $cityName && $value->parentID == $parentID && $value->region_level == 2){
    			$cityid = $value->id;
    			$parentID = $value->id;
    			if (empty($districtName)){
    				break;
    			}
    		}
    		
    		if ($value->name == $districtName && $value->parentID == $parentID && $value->region_level == 3){
    			$countyid = $value->id;
    			break;
    		}
    	}
    	
    	$return_arr = array(
    			'provinceid'	=> $provinceid,
    			'cityid'		=> $cityid,
    			'countyid'		=> $countyid
    			);
    	return $return_arr;
    }

}
